#include "statistics.hxx"

#include <util.hxx>
#include "mymutex.hxx"
#include "task.hxx"

#include <sstream>
#include <ctime>

Statistics* Statistics::instance = 0;

Statistics* Statistics::Instance(void)
{
	static Mutex mutex;

	if (instance == 0)
	{
		Util::Lock lock(&mutex);
		if (instance == 0)
		{
			instance = new Statistics();
		}
	}

	return instance;
}

void Statistics::StaIt(const Task* task)
{
	//StaUnit* staUnit = NULL;
	//std::map<string, StaUnit*>::iterator iter = staMap.find(task->Signature());
	//if (iter == staMap.end())
	//{
	//	staUnit = new StaUnit();
	//	staUnit->start = time(0);
	//	staMap[task->Signature()] = staUnit;
	//}
	//else
	//	staUnit = iter->second;

	//switch (task->action->Type)
	//{
	//case Action::QUERY:
	//	{
	//		++(staUnit->queryNum);
	//		if (action->ActionRes == Action::ACTION_RESULT_CAPTCHA_WRONG)
	//			++(staUnit->wrongCaptchaNum);
	//		else if (action->ActionRes != Action::ACTION_RESULT_NO_FOUND)
	//			++(staUnit->errorNum);
	//	}
	//	break;
	//case Action::REFRESH:
	//	++(staUnit->sustainedNum);
	//	break;
	//default:
	//	// no statistics for other action.
	//	break;
	//}
}
std::string Statistics::GetStatictics(const Task* task)
{
	StaUnit* staUnit = NULL;
	stringstream ss;

	std::map<string, StaUnit*>::iterator iter = staMap.find(task->Signature());
	if (iter == staMap.end())
	{
		ss<<task->Signature()<<" no statistics.";
		return ss.str();
	}

	staUnit = iter->second;
	ss<<task->Signature()<<" "<<time(0)-staUnit->start<<"s,"
	  <<"query:"<<staUnit->queryNum<<",wrongCap:"<<staUnit->wrongCaptchaNum<<",err:"<<staUnit->errorNum<<",refresh:"<<staUnit->sustainedNum;

	return ss.str();
}